let { HttpRequest, globalData, cloud, CloudFunction, UserAccess, mfutil, URLChangeCommon, addUserStat } = getApp();
const app = getApp();
Page({
  data: {
    imageList_num: 0,
    imageList: [],
    videoList_num: 0,
    videoList: [],
    successActive: false,//弹窗显示
    isUGCcontrols: false, // 视频控件是否显示
    loadingActive: false, // 加载控件
    videoTimer: null, // 上传视频的定时器
    json: null, // 接收上个页面传递的数据
    submitStatus: true, // 提交按钮是否可以点击
    id: null, //接受的tileID
    type: null,
    router: '/pages/showUGCList/showUGCList',
    pagetitle: '赚积分详情页',
    pageTitleVal: ""
  },
  onLoad(query) {
    console.log(JSON.parse(query.ugc_type));


    if (JSON.stringify(query) != "{}") {
      let json = {}
      json = JSON.parse(query.ugc_type)
      console.log(json, `rereeeeeeeeeeeeeeeeeeeee`)
      this.setData({
        json: { tile_info: json },
        id: json.id,
        type: json.type,
        imageList_num: json.ugc.image,
        videoList_num: json.ugc.video,
        pageTitleVal: json.complete_text
      })
    }
  },
  onShow() { },
  onUnload() {
    console.log(`页面销毁---`);
    let that = this;

    clearInterval(that.data.videoTimer);
  },

  // 点击上传视频还是图片
  getIntegral2(e) {
    let { index, item, ugc_type } = e.currentTarget.dataset;
    let event = { currentTarget: { dataset: { type: 'camera', item: '' } } }
    if (ugc_type == 'video') {
      this.videoFn(event)
    } else {
      this.cameraFn(event)
    }
  },

  /**
   * 
   * @上传图片区域
   * 
   *  */
  // 相机
  cameraFn(event) {
    // let { item, type } = event.currentTarget.dataset;
    // this.setData({
    //   item,
    //   type
    // })
    this.chooseImage()
  },

  // 上传图片 
  chooseImage(event) {
    let that = this;
    let imageList_num = this.data.imageList_num;
    // console.log(`------------imageList_num-----------------`, imageList_num)

    my.chooseImage({
      count: imageList_num,  // 最多6张
      sourceType: ['camera', 'album'],
      isClipped: false, //防止对图片进行剪裁
      success: async (chooseImageres) => {
        console.log(`-----------==chooseImageres==---------`, chooseImageres)
        let ImagesList = chooseImageres.apFilePaths;
        let chooseImageres_num = chooseImageres.apFilePaths.length;
        let chooseImageres_num_qishi = 0;

        // 显示loading
        that.setData({
          loadingActive: true
        })
        let num = 0;
        // for循环将多选的图片依次上传
        for (let [image_index, image_item] of ImagesList.entries()) {
          // 获取文件信息
          my.getFileInfo({
            apFilePath: image_item,
            digestAlgorithm: 'sha1',
            success: (getFileInfores) => {
              console.log("================================", getFileInfores)
              // 获取图片大小，最大限制为3MB
              if (getFileInfores.size > 3145728) {
                my.alert({
                  content: '请上传3MB以内的图片资源！'
                })
                if (chooseImageres_num != 1) {
                  chooseImageres_num--;
                } else if (chooseImageres_num == 1) {
                  that.setData({
                    loadingActive: false
                  })
                }
                // return;
              } else {
                let fileType = /\.[^\.]+$/.exec(image_item);
                // 上传到云存储
                cloud.file.uploadFile({
                  filePath: image_item,
                  fileType: 'image',
                  fileName: `/miniapp_res/icon_${new Date().getTime()}${fileType}`,
                  success: async (uploadFileres) => {

                    //检测图片
                    my.tb.imgRisk({
                      data: {
                        cloudFileId: uploadFileres.fileId
                      },
                      success: async (imgRiskres) => {
                        console.log(`imgRiskres------------`, imgRiskres)
                        /**
                         * @checkPoints 检测返回的图片类型数组
                         */
                        let checkPoints = imgRiskres.data.result.checkPoints;
                        /**
                         * @max_checkPoints 获取最大值的一条数据
                         */
                        let max_checkPoints_item = checkPoints.reduce((acc, cur) => {
                          if (!acc) {
                            acc = cur
                            return acc
                          }
                          if (Number(acc.rate) < Number(cur.rate)) {
                            acc = cur
                            return acc
                          }
                          return acc
                        }, 0)
                        // 判断是否是正常的图片
                        if (max_checkPoints_item.label != 'normal') {
                          my.alert({
                            content: '您上传的内容未通过审核，请更换其他内容'
                          })

                          if (chooseImageres_num != 1) {
                            chooseImageres_num--;
                          } else if (chooseImageres_num == 1) {
                            // chooseImageres_num--;
                            that.setData({
                              loadingActive: false
                            })
                          }
                          /* that.setData({
                            illegal: true
                          })
                          return */
                        } else {
                          console.log(uploadFileres.url, `-------uploadFileres--------`, image_index);
                          /**
                           * @上传接口
                           */
                          let path = `/vans-family/api/v2.1/project/vansFamily/cms/upload`;
                          let parmasObj = {
                          }
                          let bodyObj = {
                            "fileUrl": uploadFileres.url,
                            "tile_id": that.data.id,
                            "member_id": globalData.userInfo.memberId
                          }
                          let result = await HttpRequest(path, 'POST', parmasObj, bodyObj)
                          if (result.data.code == 0) {

                            console.log(`---------upload--1-------`, result.data)
                            let { imageList } = this.data;
                            imageList = { url: result.data.data.url }

                            // 求出显示几个空白的盒子 没成功上传一张图片空白盒子减一
                            let imageList_num_chazhi = this.data.imageList_num - 1;
                            that.setData({
                              imageList: this.data.imageList.concat(imageList),
                              imageList_num: imageList_num_chazhi
                            })

                            chooseImageres_num_qishi++;

                            console.log(this.data.imageList, `----------------chooseImageres_num_qishi++-------------------`, chooseImageres_num)
                            if (chooseImageres_num_qishi == chooseImageres_num) {
                              that.setData({
                                loadingActive: false
                              })
                            }
                          } else {
                            that.setData({
                              loadingActive: false
                            })
                            my.alert({
                              content: result.data.msg
                            })
                          }
                        }

                      },
                      fail() {
                        // my.alert({
                        //   content: result.data.msg
                        // })

                        my.alert({ title: '检查失败' });
                      },
                    })
                    /* if (that.data.illegal) {
                      return;
                    } */
                  },
                  error: (err) => {
                    my.showToast({
                      type: "fail",
                      content: "图片上传失败" + JSON.string(err)
                    });
                  }
                })
              }
            }
          })
        }
      },
      fail: (error) => {
        this.setData({
          videoBtn: 0
        })
        console.log(error, 'fail')
      }
    });
  },



  /**
   * 
   * @上传视频区域
   */
  //视频部分
  videoFn(event) {
    // let { item, type } = event.currentTarget.dataset;
    // this.setData({
    //   item,
    //   type
    // })
    this.chooseVideo();
  },
  // 上传视频
  chooseVideo(event) {
    let that = this;
    my.chooseVideo({
      sourceType: ['camera', 'album'],
      maxDuration: 60,
      camera: 'back',
      success: async (chooseVideores) => {
        console.log(`----------chooseVideores-----------`, chooseVideores);
        this.setData({
          loadingActive: true
        })
        //获取视频信息/大小，最大限制为30MB
        my.getFileInfo({
          apFilePath: chooseVideores.apFilePath,
          digestAlgorithm: 'sha1',
          success: (getFileInfores) => {
            if (getFileInfores.size > 31457280) {
              my.alert({
                content: '请上传30MB以内的视频资源！'
              })

              this.setData({
                loadingActive: false
              })
              return
            }

            let filetype = /\.[^\.]+$/.exec(chooseVideores.apFilePath);
            // 上传视频到云存储
            cloud.file.uploadFile({
              filePath: chooseVideores.apFilePath,
              fileType: 'video',
              fileName: `/miniapp_video/video_${new Date().getTime()}${filetype}`,
              success: async (uploadFileres) => {
                console.log(`---------vide -uploadFileres --------`, uploadFileres)
                let url = uploadFileres.url;
                that.data.videoTimer = setInterval(async () => {
                  if (!url) {
                    let urls = await cloud.file.getTempFileURL({
                      fileId: [uploadFileres.fileId]
                    })
                    console.log(`------video-urls----------`, urls)
                    console.log('666666666666666666666', that.data.id);

                    if (urls[0].status == 1) {

                      /**
                     * @上传接口
                     */
                      let path = `/vans-family/api/v2.1/project/vansFamily/cms/upload`;
                      let parmasObj = {
                      }
                      let bodyObj = {
                        "fileUrl": urls[0].url,
                        "tile_id": that.data.id,
                        "member_id": globalData.userInfo.memberId
                      }
                      let result = await HttpRequest(path, 'POST', parmasObj, bodyObj)
                      if (result.data.code == 0) {
                        // debugger
                        console.log(`---------upload-video-2-------`, result.data)
                        url = { url: result.data.data.url }
                        let { videoList } = this.data;
                        // videoList[0] = url
                        /**
                         * @判断数组不为空时传递视频去重
                         */
                        if (videoList.length > 0) {
                          for (let item of videoList) {
                            if (item.url !== url.url) {
                              this.setData({
                                videoList: this.data.videoList.concat(url),
                                videoList_num: this.data.videoList_num - 1
                              })
                            }
                          }
                        } else {
                          this.setData({
                            videoList: this.data.videoList.concat(url),
                            videoList_num: this.data.videoList_num - 1
                          })
                        }


                        this.setData({
                          loadingActive: false
                        })
                        console.log(`---------videoList---------`, this.data.videoList);

                        clearInterval(that.data.videoTimer);
                      } else {
                        that.setData({
                          loadingActive: false
                        })
                        my.alert({
                          content: result.data.msg
                        })
                      }
                    }
                  }
                }, 2000);
              },
              error: (err) => {
                my.showToast({
                  type: "fail",
                  content: "视频上传失败" + JSON.string(err)
                });
              }
            })
          },
          fail: (error) => {
            console.log(error, '000000000000000000000')
          }
        })
      },
      fail: (err) => {
        console.log(`---------err-----------`, err)
        if (err.error == -1) {
          my.showToast({
            type: 'fail',
            content: '请上传60s以内的视频!',
            duration: 1500,
          });
        }
        my.hideLoading({
          page: this,  // 防止执行时已经切换到其它页面，page指向不准确
        });
      }
    })
  },
  /**
   * @删除当前的数据
   *  */
  deletePresent(e) {
    console.log(`-------deletePresent--------`, e)
    let { listType, index } = e.currentTarget.dataset;
    let { imageList, videoList } = this.data;
    let list;
    if (listType == 'imageList') {

      list = imageList.splice(index, 1);
      this.setData({
        imageList,
        imageList_num: this.data.imageList_num + 1
      })
    } else if (listType == 'videoList') {
      list = videoList.splice(index, 1);
      this.setData({
        videoList: videoList,
        videoList_num: this.data.videoList_num + 1
      })
    }
  },






  /**
   * 
   * @提交设计
   * 
   */
  async submitDesign() {
    let that = this;
    /**
     * @提交按钮状态判断和切换
     */
    if (!that.data.submitStatus) {
      console.log(`------submitStatus--------`)
      return;
    }
    that.setData({
      submitStatus: false
    })


    console.log(`------imageList-----`, that.data.imageList)
    console.log(`------videoList-----`, that.data.videoList)
    // 完成任务
    let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
    let { imageList, videoList, json, id, type } = this.data;
    let list = [];
    for (let item of imageList) {
      list.push(item.url)
    };
    for (let item of videoList) {
      list.push(item.url)
    };
    console.log(`-----完成任务-----list----2--`, list);
    console.log(`-----完成任务-----list----3--`, id);


    let bodyObj = {
      do_datetime: time,
      ugc_media_list: list
    }

    let parmasObj = {
      member_id_type: 1,
      member_id: globalData.userInfo.memberId
    }
    console.log(bodyObj, parmasObj);

    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${type}/${id}/done`;
    let res = await HttpRequest(path, 'POST', parmasObj, bodyObj);
    console.log(`---------res-代码----------------`, res)
    if (res.data.code == 0) {
      this.setData({
        successActive: true,
        imageList: [],
        videoList: []
      })

      setTimeout(() => {
        that.setData({
          submitStatus: true
        })
      }, 2000);
    } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001 || res.data.code == 53024) {
      my.alert({
        content: res.data.msg,
        success: () => {
          that.setData({
            submitStatus: true
          })
        }
      })
    } else {
      mfutil.launchErrPage(53001)
    }

    /**
    * @用户行为记录埋点
    */
    let routerArr = getCurrentPages();
    let options = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
    };

    UserAccess(options);

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileDone_' + this.data.json.tile_info.id + '_上传完成TileDone_',
      // tileId: this.data.json.tile_info.id,
      // points: this.data.json.tile_info.points
    }
    let tracks = addUserStat(customAccessoptions)
    console.log(id, 'TileDone');

  },

  /**
   * @后台返回的按钮数组经过判断决定怎样跳转
   *  */
  urlChange(event) {
    let { item } = event.currentTarget.dataset;
    URLChangeCommon(item)

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCTA_' + this.data.json.tile_info.id + '_' + item.cta_button_name
    }

    let tracks = addUserStat(customAccessoptions)
  },


  /**@防止事件穿透 */
  loading_s() { },

  // 点击播放按钮
  UGCvideoPlay() {
    // let videoUGCuploaded = my.createSelectorQuery()
    //   .select('#videoUGCuploaded');
    // videoUGCuploaded.play()
    // console.log(videoUGCuploaded);
  },
  // 视频暂停
  UGCvideoPause() {

  }
})